/*
Copyright (c) 2009, Young Digital Planet SA
All rights reserved.

* Redistribution and use in source and binary forms, with or without 
  modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this 
  list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, 
  this list of conditions and the following disclaimer in the documentation 
  and/or other materials provided with the distribution.
* Neither the name of the Young Digital Planet SA nor the names of its 
  contributors may be used to endorse or promote products derived from this 
  software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE 
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
POSSIBILITY OF SUCH DAMAGE.
*/
package pl.ydp.nexl.impl
{
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.system.ApplicationDomain;
	
	import flexunit.framework.TestCase;
	
	import mx.core.ByteArrayAsset;
	
	import pl.ydp.nexl.INexlLibrary;
	import pl.ydp.nexl.INexlLibraryContainer;
	import pl.ydp.nexl.utils.Libraries;
	

	public class TestNexlLibraryReq extends TestCase
	{
		[Embed(source="/_res/podstawa.swf",mimeType="application/octet-stream")]
		public static var BASE_LIB:Class;
		
		[Embed(source="/_res/base2.swf",mimeType="application/octet-stream")]
		public static var BASE2_LIB:Class;
		
		[Embed(source="/_res/base3.swf",mimeType="application/octet-stream")]
		public static var BASE3_LIB:Class;
		
		[Embed(source="/_res/rozszerzenie.swf",mimeType="application/octet-stream")]
		public static var EXT_LIB:Class;
		
		[Embed(source="/_res/ext2.swf",mimeType="application/octet-stream")]
		public static var EXT2_LIB:Class;
		
			
		public static var BASE:XML =
		<library loadType="swf" src="res/podstawa.swf" id="pl.ydp.nexl1">
			<activator class="n1.Activator" />
			<ext implementation="n1.Base" >
				<attr name="type" value="Object"/>
				<attr name="shortName" value="Base" />
			</ext>
		</library>;
		
		public static var BASE2:XML =
		<library loadType="swf" src="res/base2.swf" id="pl.ydp.nexl11">
			<ext implementation="n3.Base2" >
				<attr name="type" value="Object"/>
				<attr name="shortName" value="Base2" />
			</ext>
		</library>;
		
		public static var BASE3:XML =
		<library loadType="swf" src="res/base3.swf" id="pl.ydp.nexl12">
			<ext implementation="n3.Base3" >
				<attr name="type" value="Object"/>
				<attr name="shortName" value="Base3" />
			</ext>
		</library>;
		
		public static var EXT:XML =
		<library loadType="swf" src="res/rozszerzenie.swf" id="pl.ydp.nex21">
			<requires library="pl.ydp.nexl1" />
			<ext implementation="n2.Derivative" >
				<attr name="type" value="Object"/>
				<attr name="shortName" value="Derivative" />
			</ext>
		</library>
		
		public static var EXT2:XML =
		<library loadType="swf" src="res/ext2.swf" id="pl.ydp.nexl22">
			<requires library="pl.ydp.nexl1" />
			<requires library="pl.ydp.nexl11" />
			<requires library="pl.ydp.nexl12" />
			<ext implementation="n4.Ext2" >
				<attr name="type" value="Object"/>
				<attr name="shortName" value="Derivative2" />
			</ext>
		</library>
		
		
		private function extractFile(f:Class, n:String):File {
			var dest:File = File.applicationDirectory.resolvePath("res/"+n);
			var stream:FileStream = new FileStream();
			stream.open( new File(dest.nativePath), FileMode.WRITE );
			stream.writeBytes( (new f()) as ByteArrayAsset );
			stream.close();
			return dest;
		}
		
		public function testLoad():void {
			
			var lib:NexlLibrary = new NexlLibrary("");
			lib.loadData( BASE );
			
			assertEquals( "Activator class", "n1.Activator", lib.m_activatorClass );
			assertEquals( "Number of extensions", 1, lib.m_extensions.length );
			
		}
		
		
		public function testBasicLibLoadCompletion():void {
			
			//loading simple Nexl library - with no requirements
			//should trace "loaded" 
			
			var lib:NexlLibrary = new NexlLibrary(extractFile(BASE_LIB, "base.swf").url, null ,ApplicationDomain.currentDomain);
			lib.loadData( BASE );
            
			var c1:Function = addAsync( function( ... rest ):void {
				trace( "Required library loaded successfully" ); 
				}, 5000, null, // in debug mode it may take looong (over 2sec) 
				function():void {
					fail( "Library loaded callback never comes" ); 
				} );
			lib.loadLibrary( new LibLoadMonitor(c1, monFailed) );

			
		}
		
		public function testSingleReqLibLoadCompletion():void {
			
			//loading a Nexl library with one required lib
			//inits GL to house descriptions of base (BASE) and extending (EXT) libs
			//should find, load and init required library before trying to load extending lib  
			
			var gl:GatheringLibrary = new GatheringLibrary();
			
			var preq:NexlLibrary = new NexlLibrary(extractFile(BASE_LIB, "base.swf").url, null ,ApplicationDomain.currentDomain);
			preq.loadData( BASE );
			gl.addLibrary(preq);
			
			var lib:NexlLibrary = new NexlLibrary(extractFile(EXT_LIB, "rozszerzenie.swf").url, null ,ApplicationDomain.currentDomain);
			lib.loadData( EXT );
			gl.addLibrary(lib);
			
			var c1:Function = addAsync( function( ... rest ):void {
				trace( "Simple library loaded successfully" ); 
				assertEquals( "Required library loaded: ", true, preq.m_loader.loaded );
				}, 5000, null, // in debug mode it may take looong (over 2sec) 
				function():void {
					fail( "One or more required libraries failsed to load" ); 
				} );
			
			lib.loadLibrary( new LibLoadMonitor(c1, null) );
			
			
			
		}
		
		public function testMultipleReqLibLoadCompletion():void {
			
			//loading a Nexl library with 2 required libs
			//inits GL to house descriptions of bases (BASE2 and 3) and extending (EXT2) libs
			//should find, load and init required library before trying to load extending lib  
		
			var gl:GatheringLibrary = new GatheringLibrary();
			
			var preq3:NexlLibrary = new NexlLibrary(extractFile(BASE_LIB, "base.swf").url, null ,ApplicationDomain.currentDomain);
			preq3.loadData( BASE );
			gl.addLibrary(preq3);
			
			var preq:NexlLibrary = new NexlLibrary(extractFile(BASE2_LIB, "base2.swf").url, null ,ApplicationDomain.currentDomain);
			preq.loadData( BASE2 );
			gl.addLibrary(preq);
			
			var preq2:NexlLibrary = new NexlLibrary(extractFile(BASE3_LIB, "base3.swf").url, null ,ApplicationDomain.currentDomain);
			preq2.loadData( BASE3 );
			gl.addLibrary(preq2);
			
			var lib:NexlLibrary = new NexlLibrary(extractFile(EXT2_LIB, "rozszerzenie2.swf").url, null ,ApplicationDomain.currentDomain);
			lib.loadData( EXT2 );
			gl.addLibrary(lib);
			
			var c1:Function = addAsync( function( ... rest ):void {
				trace( "All of the required libs were loaded" ); 
				assertEquals( "1st Required library loaded: ", true, preq.m_loader.loaded );
				assertEquals( "2nd Required library loaded: ", true, preq2.m_loader.loaded );
				}, 5000, null, // in debug mode it may take looong (over 2sec) 
				function():void {
					fail( "One or more required libraries failsed to load" ); 
				} );
			
			lib.loadLibrary( new LibLoadMonitor(c1, monFailed) );

		}
		
		public function testFindLibraryById():void {
			
			//FindlibraryById is a method of GatheringLibrary class
			//it should browse through GL's children and get a library matching the ID given as parameter
			
			var gl_top:GatheringLibrary = new GatheringLibrary;
			var gl_mid:GatheringLibrary = new GatheringLibrary;
			var gl_bot:GatheringLibrary = new GatheringLibrary;
			
			var lib:NexlLibrary = new NexlLibrary("");
			lib.loadData( BASE );
			var lib2:NexlLibrary = new NexlLibrary("");
			lib2.loadData( BASE2 );
			var lib3:NexlLibrary = new NexlLibrary("");
			lib3.loadData( BASE3 );
			
			gl_mid.addLibrary(gl_bot);
			gl_bot.addLibrary(lib2);
			gl_mid.addLibrary(lib);
			gl_top.addLibrary(gl_mid);
			gl_top.addLibrary(lib3); //embedding Nexl Libs and mixing them with GLs - nice XMas tree;)
			
			var sParent:INexlLibraryContainer = Libraries.findSuperParent(lib2);
			var foundLib1:IExtensionsContainer = sParent.findLibraryById(BASE.@id) as IExtensionsContainer;
			var foundLib2:IExtensionsContainer = sParent.findLibraryById(BASE2.@id) as IExtensionsContainer;
			var foundLib3:IExtensionsContainer = sParent.findLibraryById(BASE3.@id) as IExtensionsContainer;
			
			assertEquals( "1st found Lib ID should be: "+BASE.@id, BASE.@id, foundLib1.id ); //checking if found libs match expected ID
			assertEquals( "2nd found Lib ID should be: "+BASE2.@id, BASE2.@id, foundLib2.id );
			assertEquals( "3rd found Lib ID should be: "+BASE3.@id, BASE3.@id, foundLib3.id );
		}


		//
		private function monFailed(... rest):void {
			trace("load failed");
		}
		
	}
}
	import pl.ydp.nexl.impl.ILibraryLoadMonitor;
	import pl.ydp.nexl.INexlLibrary;
	

class LibLoadMonitor implements ILibraryLoadMonitor {
	
	private var successCallback:Function;
	private var failCallback:Function;
	
	public function LibLoadMonitor( sc:Function, fl:Function = null ) {
		successCallback = sc;
		failCallback = fl;
	}
	
	public function failed( ext:INexlLibrary, cause:String = null ):void {
		//trace(failCallback);
		failCallback( null );
	}
	
	public function succeeded( ext:INexlLibrary ):void {
		successCallback( null );
	}
}